import { defineStore } from 'pinia'
import { ref } from 'vue'
import {getUserinfo,updateUserThirdOpenid} from "@/api/lotos-lamp.js";

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null,
    token: null,
    isLoading: false
  }),

  actions: {
    async queryUserByToken(token) {
      if (this.isLoading) return

      this.isLoading = true
      try {
        // 保存 token
        this.token = token

        // 使用 token 获取用户信息
        const response = await getUserinfo({token})

        const userData = await response.data

        // 保存用户信息到 store
        this.userInfo = {
          openid: userData.openid,
          thirdOpenid: userData.thirdOpenid,
          nickname: userData.username,
          avatar: userData.avatar,
          // ... 其他用户信息字段
          activeLamps:0,
          totalSupplyCnt:0,
          totalAmount:0
        }

        // 将 token 和用户信息保存到 localStorage，以便页面刷新后恢复
        localStorage.setItem('token', token)
        localStorage.setItem('userInfo', JSON.stringify(this.userInfo))

        return this.userInfo
      } catch (error) {
        console.error('处理 token 失败:', error)
        // 清除可能存在的无效数据
        this.clearUserInfo()
        throw error
      } finally {
        this.isLoading = false
      }
    },
    async updateUserInfo(authData) {
      try {
        // 保存 token
        this.userInfo.thirdOpenid = authData.openid
        //alert(authData.openid)
        // 使用 token 获取用户信息
        const response = await updateUserThirdOpenid({openid:this.userInfo.openid, thirdOpenid:authData.openid})
        localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
        //alert(JSON.stringify(this.userInfo))
        return this.userInfo
      } catch (error) {
        console.error('处理 token 失败:', error)
        // 清除可能存在的无效数据
        this.clearUserInfo()
        throw error
      }
    },



    // 清除用户信息
    clearUserInfo() {
      this.token = null
      this.userInfo = null
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    },

    // 初始化时从 localStorage 恢复用户信息
    initUserInfo() {
      const token = localStorage.getItem('token')
      const userInfo = localStorage.getItem('userInfo')

      if (token && userInfo) {
        this.token = token
        this.userInfo = JSON.parse(userInfo)
      }
    }
  },

  // 添加持久化
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'user',
        storage: localStorage,
        paths: ['token', 'userInfo']
      }
    ]
  }
})
